package pers.cz.commons.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: PostGirl-panent
 * @description: DataSourceFactory
 * @author: Cheng Zhi
 * @create: 2021-12-28 15:00
 **/
@Configuration
public class DataSourceFactory {

    @Autowired
    private DataSourceMaster dataSourceMaster;

    @Autowired
    private DataSourceDev dataSourceDev;

    @Bean(name = "master")
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dataSourceMaster.getUrl());
        dataSource.setUsername(dataSourceMaster.getUsername());
        dataSource.setPassword(dataSourceMaster.getPassword());
        dataSource.setDriverClassName(dataSourceMaster.getDriverClassName());
        return dataSource;
    }

    @Bean(name = "dev")
    public DataSource slaveDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dataSourceDev.getUrl());
        dataSource.setUsername(dataSourceDev.getUsername());
        dataSource.setPassword(dataSourceDev.getPassword());
        dataSource.setDriverClassName(dataSourceDev.getDriverClassName());
        return dataSource;
    }

    @Primary
    @DependsOn({ "master", "dev"}) //解决数据库循环依赖问题
    @Bean(name = "multiDataSource")
    public DynamicDataSource exampleRouteDataSource() {
        DynamicDataSource multiDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("master", masterDataSource());
        targetDataSources.put("dev", slaveDataSource());
        multiDataSource.setTargetDataSources(targetDataSources);
        multiDataSource.setDefaultTargetDataSource(masterDataSource());
        return multiDataSource;
    }

    @Bean("dataSourceTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
